#include "BaseChannel.h"
#include "NetPacketPool.h"
#include "NetPeer.h"
#include "NetPacket.h"

// 完成

namespace LiteNetLib
{
    BaseChannel::~BaseChannel()
    {
        clear();
    }

    BaseChannel::BaseChannel(NetPeer *netPeer) : m_netPeer(netPeer), m_isInPeerChannelSendQueue(false) {}

    void BaseChannel::addToQueue(NetPacket *netPacket)
    {
        m_outgoingQueue.push(netPacket);
        addToPeerSendQueue();
    }

    void BaseChannel::clear()
    {
        NetPacket *netPacket = nullptr;
        while (m_outgoingQueue.try_pop(netPacket))
        {
            NetPacketPool::GetInstance().recycleOrDelete(netPacket);
        }
    }

    bool BaseChannel::sendAndCheckQueue()
    {
        bool hasPacketsToSend = sendNextPackets();
        if (hasPacketsToSend == false)
        {
            m_isInPeerChannelSendQueue = false;
        }
        return hasPacketsToSend;
    }

    void BaseChannel::addToPeerSendQueue()
    {
        if (false == m_isInPeerChannelSendQueue.exchange(true))
        {
            m_netPeer->addToReliableChannelSendQueue(this);
        }
    }

} // namespace LiteNetLib
